package com.example.bankseckill.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.bankseckill.mapper.OrderMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: liyangjing
 * @Date: 2022/03/07/21:26
 * @Description:
 */
@Slf4j
@Api(tags = "支付模块")
@Controller
@RequestMapping("/bank/alipay")
public class AliPayReturnAndNotifyController {


    @Autowired
    private OrderMapper orderMapper;

    //appid
    private final String APP_ID = "2021000118637694";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDaF+VIZaLFjPZ4i7FbggV8k1UUTaDYWZgTvLGTzvpAjL8q3lF2cKM+Z0h8uZjsVj8BopA1NNZ5mVHsxogeIpudbrqxLyuKWVmZDRqygc9cvKeFRiVDf1/DEYHHsr4h4+F0NPkX2T3Y3e+95yhB9tLY3BlRAfmQRSeE0kathJ9TkrTc8ZTc7DuhqvBXoxonmMbc6YwLv+6RngWGwm9LejYCL7Y/F38BLRjgNwmYd4FPe/pAP/uCE7ZIpKBYtKK7xhsXZhDq5UXB7wi/e2Es1JOOa1DWfmDtFImTJ5Setne/QW1FS3+wR/jEoXz/FnIxMBcQBeac/urnl2gh5nqFKpKpAgMBAAECggEBAJQYu+rAkZqikU/kVEh2b3Fbvt9to3amyF1GujNLzqX8rWfX1eueq0uZ6SBBC/YYzuo2UMTAn4+tLHOjkRUdnRx377CX/nIRIIWM338uJPitZvhaXL2MBiQ5hC5uUyxCSXuW6TtnmtbkRoNnL/AzQpReSZa3x5dPTnmkLLhxoZumduqT9/MG9O1dTZ/ORdv7vDl5HjUXfEQlpvb4RGQatooVa/lwy14hN43ixBkm/XxWNIeYIYPIQmaWpLFfImRWv7BFP9v3fMIjECWtEYbrmw+laP4c0g4W81mAu/6z8oTFO6VpbtB6OCt5LNspA7aobjEi/re8y7N1GhXnsLGAVDECgYEA/0iLERFa3CBW/actjk8W551T6PHTtm2HHqX6R40T8TNa3MEjhCTr1TzwPxWpwonB8tbvfKCI52zhnGEobObguhQ3OlFI+K5yyr1nx1CNMgK6pdsPXQScEV+K5h5cIuVR10qZppc3DMK5kz7kvcC/acdzoyiOXnQZR6p3SUNIsmUCgYEA2rSgTPUW4ZsY8gtdgkK+z+BwADhiMZLmGQG/ZeKQefG4WJNF2XfO/QmpeszUwm3U2m8yA07Z3M2dx0jb8inFrV08yvwSn8xPx7YIuNZaYxvfMJc0XNRcLq7c6QqPlJEWsbU+yuVMxDDiSoQcYZ+da4qjBuIlmQqvSK0JZOVO+PUCgYBgd0w9xd4cwoe80DixxwczvMrhgshq7laZ6UR7Vz9K7QoP01gVblJDwQRUAl6k6aOFnVzgLlWthgJ3MmuxQ0l2Z387JU460skD/bDCq5i/ZjKby/yxPLWxBvaY4K4WbauQfFs1jXy68LZpguGzJqvuT/VNmVy7KooG/86Vu7wz1QKBgCDWXfswEW9uSiCNdEzKmLu9hxOBY7ztwX6ftI0np2mn0XX7JtGwG3QCr1+wwYEv3HWvnGLCxBNTDA2P8vY5L2UISshvcJxtoMzrmAOoq4mV9bzl9wa5G94mgyS6YTR9VFr6S6NLKmuKq29kxp4hyREMj83Ixrxjzk2rLW3owCLBAoGBAN1MHS6CPRWnsNgOvq4CV1IxbcLXYuh4OkFjLT6q2SkRgakSoDS39G+EXGq/8LP3qvE9uZFXBovaRvbAuH8eybH8rQ0lMlk+2vDLuv3238WQ7SBfLbKfKnXk7sQ9POS9p0x7qpqPZDPv1Mfp0lOeUXVZGm2QP7ektFWMUikgDq2Y";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhBUe1DRcwWnP+CrS+3rTAxmpBFv6FGyvjWX+av5v+R3k1Qgo9PoaWyGhHAh0tW7T7iqmynF84JXNKeK5VM8t8HUfY0N3GIzJePuhEk0cJnRoVjnDYpl8Xa3wFfEw6Cn11iDSaJgMWNMBPhckA2GjZSnF4qjYOAiGn7oTjVNfvEaibzUaazIKNDxEH40xHLK6ozfJXY1ogKtcmf4jgfxfL7900ql36AbDkWS7XTeKiDPECEI6CZUoaUQ1m8i/QX7+U1ZJmNmhUCV3BhcI1BUQKMjFoYjHt1XLtjqLjkzxvoqLSF5m+EZRAdVt8qXdDFOMRirXGgy8GGpzL0p0K9WmtwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://81.70.146.198:8081/bank/alipay/notify";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://81.70.146.198:8081/bank/alipay/ReturnNotify";

//    @GetMapping("/ReturnNotify")
    @ApiOperation(value = "同步回调接口，不需要在公网上")
    @RequestMapping(value = "/ReturnNotify",method = RequestMethod.GET)
    public String returnUrlMethod(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        log.info("================同步回调============");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            log.info("商户订单号="+out_trade_no);
            log.info("支付宝交易号="+trade_no);
            log.info("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
			/*
			################################
			*/
            //跳转到提示页面（成功或者失败的提示页面）
//           TODO 本地地址 如果上线放服务器地址
            return "redirect:http://47.108.83.249/#/user/myOrder";
        }else{
            log.info("验签失败");
            //跳转到提示页面（成功或者失败的提示页面）
            return "redirect:http://47.108.83.249/#/user/myOrder";
        }
    }


    @ApiOperation(value = "支付宝异步回调接口，需要设置在公网上")
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        log.info("进入回调");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.info("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");

            // 支付宝验签
            if (AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单 已支付 状态 1
                orderMapper.updateState(Integer.valueOf(tradeNo), 1, gmtPayment);
            }
        }
        return "redirect:http://47.108.83.249/#/user/myOrder";
    }
}
